package com.lsk.task;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.lsk.api.*;
import com.lsk.util.DateUtil;
import com.lsk.util.JsonUtil;
import com.lsk.util.Syslog;
import org.apache.commons.lang.StringUtils;

import java.util.List;

public class SendCardTask implements Runnable {



    @Override
    public void run() {

        Cache cache = Redis.use();

        Syslog.info("推卡线程启动");

        cache.setex("sendCard",10,"sendCard");

        //YJFService.queryCardState();//查询易缴费卡状态

        /*查询接口开关*/

        String confiSql = "select value from sys_config where element=";


        int xkstate = Integer.parseInt(Db.queryStr(confiSql + "'xkstate'"));//闲卡

        int yjfstate = Integer.parseInt(Db.queryStr(confiSql + "'yjfstate'"));//易缴费

        int sklstate = Integer.parseInt(Db.queryStr(confiSql + "'sklstate'"));//收卡啦

        int sxkstate= Integer.parseInt(Db.queryStr(confiSql + "'suxiaoka'"));//速消卡

        int mifengstate = 1;
        String nifeng = Db.queryStr(confiSql + "'mifeng'");
        if (StringUtils.isNotBlank(nifeng)) {
            mifengstate= Integer.parseInt(nifeng);
        }

        String date = DateUtil.getDay();


        String yesterday=DateUtil.getAfterDayDate("-1").substring(0,10);
        /*查询今天未同送的卡*/

        String sql = "SELECT *from card where state=0 and  (DATE_FORMAT(upTime,'%Y-%m-%d')='" + date + "' or DATE_FORMAT(upTime,'%Y-%m-%d')='"+yesterday+"' ) ";
        List<Record> cards = Db.find(sql);

        for (int i = 0; i < cards.size(); i++) {
            /*查询推送优先级*/
            Record temp = cards.get(i);
            String newCardId = temp.getStr("id");

            // 已经推送
            Object object= cache.get("send"+newCardId);
            if (object != null){
                continue;
            }

            // 正在推送
            Object sendingCard = cache.get("sending:" + newCardId);
            if (sendingCard != null) {
                continue;
            }
            cache.setex("sending:" + newCardId,90, newCardId);

            Syslog.info("待推送卡共："+cards.size()+"张");
            Syslog.info("卡信息："+ JsonUtil.getJsonStr(cards));

            String faceValueId = temp.getStr("feedbackId");
            String sendSql = "SELECT *from commodity_api_number where faceValueId='" + faceValueId + "' order by number ";
            Record first = Db.findFirst(sendSql);

            if (first != null) {
                // 已配置可进行配送
                Syslog.info(first);

                int apiType = first.getInt("apiType");

                if (apiType == 0) {
                    // 易缴费

                    Syslog.info("该商品接口为易缴费");
                    if (yjfstate == 0) {
                        // 易缴费接口已开通
                        Syslog.info("该商品接口为易缴费");
                        cache.setex("send"+newCardId,60,newCardId);
                        YJFService.cardSubmit(temp);
                    } else {
                        //易缴费接口未开通
                        Db.update("update card set state =?, msg=? where id =?", 7,
                                "易缴费接口未开通，不进行推送", newCardId);
                    }
                } else if (apiType == 1) {
                    // 闲卡网

                    if (xkstate == 0) {
                        // 闲卡网接口开通

                        /** 查找commodity_facevalue 中xkCommodityId ,查找 下列三个参数    */
                        String xkCommodityDetailId = Db.queryStr("select xkCommodityId from commodity_facevalue where id =(select feedbackId from card where id =?)", temp.getStr("id"));
                        Record xkCommodity = Db.findFirst("select * from xy_commodity where commodityDetailId =?", xkCommodityDetailId);

                        if (xkCommodity != null) {
                            XKService.cardSubmit(temp);
                        } else {
                            temp.set("msg", "未配置闲卡商品信息").set("state",7);
                            Db.update("update card set state =1,msg=? where id =? ","未关联闲卡商品",newCardId);
                        }
                    } else {
                        temp.set("msg", "闲卡网接口未开通，不进行推送").set("state", 7);
                        Db.update("update card set state =1,msg=? where id =?","闲卡网接口未开通",newCardId);
                    }

                    temp.remove("returnJson");
                    Object o = cache.get("card_send_logs" + newCardId);
                    if (o != null) {
                        Record sendLog = (Record) o;
                        temp.set("msg", sendLog.getStr("returnMsg"));
                    }
                } else if (apiType == 2) {//收卡啦

                    if (sklstate == 0) {//收卡啦接口开通
                        /**根据cardId获取 commodity_facevalue skid**/
                        String skCommodityId = Db.queryStr("select skCommodityId from commodity_facevalue where id = (select feedbackId from card where id =?)", temp.getStr("id"));
                        if (skCommodityId == null || "".equals(skCommodityId)) {
                            temp.set("msg", "未关联收卡啦商品").set("state", 7);
                            Db.update("update card set state=? , msg =? where id =?", temp.getStr("state"), temp.getStr("msg"), newCardId);
                            Syslog.info("未配置过收卡商品信息");
                        } else {        //配置过收卡啦商品,进行提交
                            SKService.cardSubmit(temp);
                        }
                    } else {
                        temp.set("msg", "收卡啦接口未开通，不进行推送").set("state", 7);
                        Db.update("update card set state=1 ,msg=? where id=?","收卡啦接口未开通,不进行推送",newCardId);
                    }

                    temp.remove("returnJson");

                    //  Db.update("card", "id", temp);

                    Object o = cache.get("card_send_logs" + newCardId);

                    if (o != null) {

                        Record sendLog = (Record) o;

                        temp.set("msg", sendLog.getStr("returnMsg"));

                    }

                } else if (apiType == 3){
                    // 速效卡



                    if (sxkstate == 0) {
                        // 速消卡  接口开通
                        /**根据cardId获取 commodity_facevalue skid**/

                        String checkSql="SELECT *from commodity_facevalue WHERE commodityId='"+temp.get("commodityId")+"'";

                        Record sxk=Db.findFirst(checkSql);
                        if (sxk==null) {
                            temp.set("msg", "未关联到速销卡产品，无法推送").set("state", 7);
                            Db.update("update card set state=? , msg =? where id =?", temp.getStr("state"), temp.getStr("msg"), newCardId);
                            Syslog.info("未配置过速销卡产品，无法推送");
                        } else {
                            // 配置过收卡啦商品,进行提交

                            // 查询速效卡产品
                            String sxkProdectSql="SELECT code from commodity_sxk where id="+sxk.getStr("sxkCommodityId")+"";


                            Record sxkRecord=Db.findFirst(sxkProdectSql);

                            if (sxkRecord==null){
                                temp.set("msg", "未关联到速销卡产品，无法推送").set("state", 7);
                                Db.update("update card set state=? , msg =? where id =?", temp.getStr("state"), temp.getStr("msg"), newCardId);
                                Syslog.info("未配置过速销卡产品，无法推送");

                            }else {

                                String code=sxkRecord.getStr("code");

                                Syslog.info("产品代码:>>>"+code);

                                temp.set("productCode",code);
                                //查询卡类别,判断是否是加油卡
                                String commodetyClassSql="SELECT *from commodity_class where id='"+temp.getStr("classId")+"'";

                                Record commodityClass=Db.findFirst(commodetyClassSql);

                                if (commodityClass.getStr("refuel") .equals("1")){
                                    // 是加油卡

                                    SXKService.cardSubmitRefuel(temp);

                                }else {

                                    SXKService.cardSubmit(temp);
                                }

                            }
                        }
                    } else {
                        temp.set("msg", "速销卡接口未开通，不进行推送").set("state", 7);
                        Db.update("update card set state=1 ,msg=? where id=?","速销卡接口未开通,不进行推送",newCardId);
                    }

                    temp.remove("returnJson");

                    //  Db.update("card", "id", temp);

                    Object o = cache.get("card_send_logs" + newCardId);

                    if (o != null) {

                        Record sendLog = (Record) o;

                        temp.set("msg", sendLog.getStr("returnMsg"));

                    }

                    //完成推送

                    cache.setex("send"+newCardId,3600,newCardId);

                }else if (apiType == 4){
                    Syslog.info("推送到蜜蜂平台");

                    if (mifengstate == 0) {
                        //蜜蜂平台 推送开启
                        Mifeng.cardSubmit(temp);
                    } else {
                        temp.set("msg", "蜜蜂接口未开通，不进行推送").set("state", 7);
                        Db.update("update card set state=1 ,msg=? where id=?","蜜蜂接口未开通,不进行推送",newCardId);
                    }

                    temp.remove("returnJson");

                    Object o = cache.get("card_send_logs" + newCardId);

                    if (o != null) {
                        Record sendLog = (Record) o;
                        temp.set("msg", sendLog.getStr("returnMsg"));
                    }

                    // 完成推送
                    cache.setex("send"+newCardId,3600,newCardId);
                } else {
                    Syslog.error("卡：" + temp.toJson() + "未匹配到对应推送平台");
                }


            } else {

                Syslog.info("未配置序号不可推送");

                temp.set("msg", "当前商品未配置推送序号，无法推送").set("state", 7);
                /***未配置序号,不推送
                 */
                Db.update("update card set state =7,msg=? where id =?","当前商品未配置推送序号，无法推送",newCardId);


            }


        }

    }
}
